package com.sky.base.security.filter;

import com.sky.base.security.pojo.LoginUser;
import com.sky.base.security.utils.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * token过滤器
 *
 * @author 尹稳健~
 * @version 1.0
 * @time 2022/8/13
 */
@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private TokenUtil tokenUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 从header中取出token校验
        LoginUser loginUser = tokenUtil.getLoginUser(request);
        if (!Objects.isNull(loginUser) && Objects.isNull(SecurityContextHolder.getContext().getAuthentication())) {
            // 刷新token，防止token过期
            tokenUtil.verifyToken(loginUser);
            // 将登录的对象封装，获取权限信息authentication
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, null);
            // Todo 未知，可能是放验证码的
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            // 存入securityContextHolder
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        filterChain.doFilter(request,response);
    }
}
